﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using LumenWorks.Framework.IO.Csv;

namespace FrontEnd
{
	/// <summary>
	/// Interaction logic for Import.xaml
	/// </summary>
	public partial class Import : Window
	{
		public Import()
		{
			InitializeComponent();
		}

		private void Rectangle_MouseMove(object sender, MouseEventArgs e)
		{
			
		}

		private void FileValidating(object sender, FileValidatingEventArgs e)
		{
			// check file exists and is not empty
			bool isValid = false;
			if (File.Exists(e.Path))
			{
				var lines = File.ReadAllLines(e.Path);
				if(lines.Count() != 0)
				{
					isValid = true;
				}
			}

			e.Cancel = !isValid;
		}

		private void FileValidated(object sender, string filePath)
		{
			DataTable dt = new DataTable();
			bool hasHeaders = chkHasColumnNames.IsChecked.Value;

			using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(filePath), hasHeaders))
			{
				// deal with headers, add simple ones if none found
				if (hasHeaders)
				{
					foreach (var header in csv.GetFieldHeaders())
						dt.Columns.Add(new DataColumn(header));
				}
				else
				{
					for (int i = 0; i < csv.FieldCount; i++)
						dt.Columns.Add(new DataColumn(string.Format("Column{0}", i)));
				}

				// create rows
				while (csv.ReadNextRecord())
				{
					var rowVals = new string[csv.FieldCount];
					for (int i = 0; i < csv.FieldCount; i++)
					{
						rowVals[i] = csv[i];
					}

					dt.Rows.Add(rowVals);
				}
			}

			// bind
			grdImportData.DataContext = dt;
		}
	}
}
